/**
 * FssConfigFactory.java
 */
package fss.core.config;

import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import fss.core.FssException;
import fss.core.FssThrowable;

/**
 * The main configuration file factory.
 * <p>
 * The different configurations for the application can be obtained by
 * calling the various 'get' methods.
 * 
 * @author thinh
 *
 */
public class FssConfigFactory {
    /**
     * The configuration file name.
     */
    private static final String CONFIG_FILENAME = "fss-config.xml";
    /**
     * The singleton.
     */
    private static FssConfigFactory instance = null;
    /**
     * The SAX parser.
     */
    private SAXParser parser = null;
    /**
     * the config file object.
     */
    private File configFile = null;
    /**
     * The Registry Server Configuration object.
     */
    private ServiceRegistryConfig serviceRegistryConfig = null;
    
    /**
     * Hidden constructor.
     */
    private FssConfigFactory() {
        setup();
    }
    /**
     * Get the instance.
     * @return the singleton.
     */
    public static FssConfigFactory getInstance() {
        if(instance == null) {
            instance = new FssConfigFactory();
        }
        return instance;
    }    
    /**
     * Get the Registry Server Configuration object.
     * @return the RegistryServerConfig object.
     * @throws FssException on error.
     */
    public ServiceRegistryConfig getRegistryServerConfig() {
        if(serviceRegistryConfig == null) {
            try {
                ServiceRegistryConfigHandler handler = new ServiceRegistryConfigHandler();
                parser.parse(configFile, handler);
                serviceRegistryConfig = handler.getConfig();
            } catch (Exception e) {
                throw new FssThrowable(e);
            }
        }
        return serviceRegistryConfig;
    }
    /**
     * Set up the factory.
     * @throws FssException error in setup.
     */
    private void setup() {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // no need to support xml namespaces.
        factory.setNamespaceAware(false);
        // no validation required
        factory.setValidating(false);
        try {
            parser = factory.newSAXParser();
        } catch (Exception e) {
            throw new FssThrowable("Cannot intialize the configuration file", e);
        }        
        configFile = new File(CONFIG_FILENAME);
    }
}
